<template>
  <el-dialog v-model="dialogFormVisible" @close="handleClose" :close-on-click-modal="false" :title="title"
             width="90%" top="5px">
    <div class="kva-container">
    <div class="kva-contentbox">
      <home-page-header>
        <div class="kva-form-search">
          <el-form class="search-form" :inline="true" :model="queryParams" ref="searchForm">
            <el-form-item prop="keyword">
              <el-button type="danger" icon="Delete" v-if="selectIds.length > 0 " style="margin-right: 5px" @click="handleBatchRemove">批量删除</el-button>
              <el-button type="success" icon="Check" v-if="selectIds.length > 0 " style="margin-right: 5px" @click="handleBatchRecover">批量恢复</el-button>
            </el-form-item>
            <el-form-item prop="keyword">
              <el-input v-model="queryParams.keyword" placeholder="广告名称" maxlength="100" clearable/>
            </el-form-item>
              <el-form-item label="广告商：" prop="advertiserId">
                <el-select v-model="queryParams.advertiserId" @change="handleSearch" clearable class="m-2" style="width: 150px" placeholder="请选择广告商">
                  <el-option
                      v-for="item in advertment"
                      :key="item.id"
                      :label="item.nickname"
                      :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="广告类型" prop="type">
                <el-select v-model="queryParams.type" @change="handleSearch" class="m-2" clearable
                           style="width: 150px"
                           placeholder="请选择广告类型">
                  <el-option
                      v-for="item in typeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            <el-form-item>
              <el-button type="success" icon="Search" @click.prevent="handleSearch">搜索</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table v-loading="tableLoading"
                  @selection-change="handleSelectionChange"
                  :data="tableData" stripe border height="calc(100vh - 330px)">
          <el-table-column type="selection" width="55" />
          <el-table-column fixed :label="'总数：' + total" width="150" align="center">
            <template v-slot='scope'>
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed label='广告封面' width="200" align="center">
            <template v-slot='scope'>
              <img :src='scope.row.cover' width='140' height='70'>
            </template>
          </el-table-column>
          <el-table-column label='广告名称' prop='name'  align='center'/>
          <el-table-column label='广告商' prop='advertiserName' align='center'/>
          <el-table-column align='center'  label='广告功能类型'>
            <template v-slot='scope'>
             <span v-for="item in typeList" :key="item.value" >
                <span  v-if="scope.row.type === item.value">{{item.label}} / (编号：{{item.value}})</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="300">
            <template #default="scope">
              <el-button icon="remove" type="danger" @click.stop="handleRemove(scope.row)">彻底删除</el-button>
              <el-button icon="Check" type="success" @click.stop="handleRecover(scope.row)">恢复删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="kva-pagination-box center">
          <el-pagination :current-page="queryParams.pageNo" :page-size="queryParams.pageSize"
                         layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"/>
        </div>
      </home-page-header>
    </div>
  </div>
  </el-dialog>
</template>

<script setup>
import KVA from '@/utils/kva.js'
import {
  batchRecovers,
  batchRemoves,
  findPagesRecyle,
  recoverById,
  removeById,
} from '@/api/advert/advert.js'
import {getList} from "@/api/advert/advertment.js";

// 定义响应式得列表数据容器
const tableData = ref([])
const selectIds = ref([])
let tableDataCopy = []
const tableLoading = ref(false)
const pages = ref(0)
const total = ref(0)
const searchForm = ref({})
const advertment=ref([])
// 编辑添加相关
const addRef = ref({})
const emits = defineEmits(["load"])
// 控制弹窗得显示
const dialogFormVisible = ref(false)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 30,
  status: "",
  keyword: "",
  deleted:0,
  type: 1,
  advertiserId:""
})

const typeList = ref([
  {label: '首页广告', value: 1},
  {label: '课程广告', value: 2},
  {label: '文章广告', value: 3},
  {label: '个人中心广告', value: 4},
  {label: '文章明细广告', value: 5},
  {label: '课程明细广告', value: 6},
  {label: '悬浮广告', value: 7},
  {label: '小册广告', value: 8},
  {label: '小册明细广告', value: 9},
  {label: '专题广告', value: 10},
  {label: '专题明细广告', value:11},
  {label: '个人社区广告', value: 12},
])

// 加载数据
const handleLodeData = async () => {
  tableLoading.value = true
  const resp = await findPagesRecyle(queryParams)
  tableLoading.value = false
  tableData.value = resp.data.records
  tableData.value.forEach((advert, index) => {
    const currentDate = new Date();
    const startDate = new Date(advert.validStartTime);
    const endDate = new Date(advert.validEndTime);
    if (currentDate < startDate) {
      tableData.value[index].expired = 2;
    } else if (currentDate >= startDate && currentDate <= endDate) {
      tableData.value[index].expired = 0;
    } else {
      tableData.value[index].expired = 1;
    }
  });

  tableDataCopy = [...resp.data.records]
  total.value = resp.data.total * 1
  pages.value = resp.data.pages * 1
}
const handleDeleted = async (row,field) => {
  try{
    const res= await updateStatus(row.id,field,0)
    handleLodeData()
    if(res.code==20000){
      KVA.notifySuccess("操作成功!")
    }
  }catch (e){
  }
}

const hanleLoadAdvertMent=async () => {
  const res = await getList()
  advertment.value=res.data
}

// 搜索
const handleSearch = () => {
  queryParams.pageNo = 1
  handleLodeData()
}

// 重置
const handleReset = () => {
  searchForm.value.resetFields()
  handleSearch()
}

// 分页size更改
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  handleLodeData()
}

// 分页pageNo更改
const handleCurrentChange = (pno) => {
  queryParams.pageNo = pno
  handleLodeData()
}

// 彻底删除
const handleRemove = (row) => {
  KVA.confirm("警告", "<strong>您确定要执行此次【彻底删除】操作吗？</strong>", {icon: "success"}).then(async () => {
    const opid = row.id
    await removeById(opid)
    KVA.notifySuccess("彻底删除成功!")
    handleLodeData()
  })
}

// 恢复删除
const handleRecover= (row) => {
  KVA.confirm("警告", "<strong>您确定要执行【恢复删除】操作吗？</strong>", {icon: "success"}).then(async () => {
    const opid = row.id
    await recoverById(opid)
    KVA.notifySuccess("恢复成功!")
    handleLodeData()
  })
}


/**
 * 批量删除
 */
const handleBatchRemove = ()=>{
  if(selectIds.value && selectIds.value.length == 0){
    KVA.notifyError("请选择一个项进行操作！")
    return
  }

  KVA.confirm("警告", "<strong>您确定要执行此次【批量删除】操作吗？</strong>", {icon: "success"}).then(async () => {
    const ids = selectIds.value.join(",")
    await batchRemoves(ids)
    KVA.notifySuccess("批量删除成功!")
    handleLodeData()
  })
}


/**
 * 批量恢复
 */
const handleBatchRecover = ()=>{
  if(selectIds.value && selectIds.value.length == 0){
    KVA.notifyError("请选择一个项进行操作！")
    return
  }

  KVA.confirm("警告", "<strong>您确定要执行此次【批量恢复】操作吗？</strong>", {icon: "success"}).then(async () => {
    const ids = selectIds.value.join(",")
    await batchRecovers(ids)
    KVA.notifySuccess("批量恢复成功!")
    handleLodeData()
  })
}


const handleOpen = () => {
  dialogFormVisible.value = true
  handleLodeData()
  hanleLoadAdvertMent()
}

const handleClose = ()=>{
  dialogFormVisible.value = false
  emits("load")
}

/**
 * 选择删除的元素
 * @param rows
 */
const handleSelectionChange = (rows)=>{
  selectIds.value = rows.map(c=>c.id)
}

defineExpose({
  handleOpen
})


</script>